﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tool.Helper;
using Tool.Helper.Dm;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace DmWordReplaceEx
{
    public partial class WordReplace : Form
    {
        public WordReplace()
        {
            InitializeComponent();
            //_dm = new DmHelperEx();
            //_dm.Init();
            this.lbl_notice.Text = "";
            //HotKeyHelper.AddHotKey("btnStart", Keys.Shift | Keys.A, (s, e) =>
            //{
            //    btn_start_Click(null, null);
            //    e.Handled = true;
            //});
            //HotKeyHelper.AddHotKey("btnStop", Keys.Shift | Keys.S, (s, e) =>
            //{
            //    btn_stop_Click(null, null);
            //    e.Handled = true;
            //});
            this.lbl_notice.BackColor = Color.Transparent;
        }
        //DmHelperEx _dm;
        bool isRun = false;
        MSWordHelper wordHelper = new MSWordHelper();
        List<SheetTitleInfo> dict = new List<SheetTitleInfo>
            {
                new SheetTitleInfo(){TitleStr="替换",FieldStr="ReplaceStr",ColumnWidth=3000},
                new SheetTitleInfo(){TitleStr="查找",FieldStr="FindStr",ColumnWidth=3000}
            };
        private void btn_choose_Click(object sender, EventArgs e)
        {
            OpenFileDialog dia = new OpenFileDialog();
            dia.Filter = "工作簿文件（*.xlsx）|*.xlsx|97-2003工作簿文件（*.xls）|*.xls";
            if (dia.ShowDialog() == DialogResult.OK)
            {
                tbx_path.Text = dia.FileName;
            }
        }

   
        private void btn_start_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tbx_path.Text))
            {
                MessageBox.Show("请选择Excel文件", "提示", MessageBoxButtons.OK);
                return;
            }
            if (string.IsNullOrEmpty(tbx_wordPath.Text))
            {
                MessageBox.Show("请选择Word文件", "提示", MessageBoxButtons.OK);
                return;
            }
            if (isRun)
            {
                return;
            }
            isRun = true;

            ExcelHelperEx excel = new ExcelHelperEx();
            excel.ReadExcelInit(tbx_path.Text);
            
            var listData = excel.ExcelToEntity<ExcelREsult>(dict, 0);
            listData = listData.Where(p => !string.IsNullOrEmpty(p.FindStr)).ToList();
            excel.Dispose();
            progressBar1.Maximum = listData.Count;
            Task.Run(() =>
            {

                try
                {
                    wordHelper.OpenDocument(tbx_wordPath.Text);
                    int x = 1;
                    string replacePrefix = tbx_replacePrefix.Text;
                    string replaceSuffix = tbx_replaceSuffix.Text;
                    bool isAllReplace = cbx_AllReplace.Checked;
                    foreach (var item in listData)
                    {
                        do
                        {
                            if (!isRun || !wordHelper.FindReplace(item.FindStr, replacePrefix + item.ReplaceStr + replaceSuffix))
                            {
                                break;
                            }
                        }
                        while (isAllReplace);

                        this.Invoke(new Action(() =>
                        {
                            progressBar1.Value = x;
                            lbl_notice.Text =x.ToString()+"/"+listData.Count;
                            x++;
                        }));

                    }
                    var arrays = tbx_wordPath.Text.Split('.');
                    string newPath = arrays[0] + "-1" + "." + arrays[1];
                    wordHelper.SaveDocument(newPath);
                   
                }
                finally
                {
                    isRun = false;
                    wordHelper.CloseDocument();
                }
                MessageBox.Show("替换完成","提示",MessageBoxButtons.OK);
            });   
        }

        private void btn_stop_Click(object sender, EventArgs e)
        {
            isRun = false;
        }

        private void tbn_wordChoose_Click(object sender, EventArgs e)
        {
            OpenFileDialog dia = new OpenFileDialog();
            dia.Filter = "Word文件（*.docx）|*.docx|97-2003 Word文件（*.doc）|*.doc";
            if (dia.ShowDialog() == DialogResult.OK)
            {
                tbx_wordPath.Text = dia.FileName;
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
           
        }

        private void btn_dowlloadTemplate_Click(object sender, EventArgs e)
        {
            SaveFileDialog dia = new SaveFileDialog();
            dia.Filter = "工作簿文件（*.xlsx）|*.xlsx|97-2003工作簿文件（*.xls）|*.xls";
            string fielPath ;
            if (dia.ShowDialog() == DialogResult.OK)
            {
                fielPath = dia.FileName;
            }
            else{
                return;
            }
            ExcelHelperEx excel = new ExcelHelperEx();
            List<ExcelREsult> list = new List<ExcelREsult>()
            {
                new ExcelREsult(){FindStr="( ",ReplaceStr="Test1"},
                new ExcelREsult(){FindStr="( ",ReplaceStr="Test2"},
                new ExcelREsult(){FindStr="( ",ReplaceStr="Test3"}
            };
            excel.EntityToExcel(fielPath, dict, list, "查找替换");
            excel.CreateSheet("About");
            excel.SetColumnWidth(0, 20000);
            excel.SetValue(0, 0, "1.查找的关键字可以是相同的，也可以是不同的。");
            excel.SetValue(1, 0, "2.当关键字相同时，查找为从文档前面向后查找，一一匹配。");
            excel.SetValue(2, 0, "3.当未查找到关键字时，程序会结束替换，保存为新文档。");
            excel.SetValue(3, 0, "4.当勾选上“全替换”选项时，会将同一关键字全部替换后再替换下一个，仅为关键字不同时使用。");
            excel.SetValue(4, 0, "5.本功能使用场景为：有一个Word表需要进行批量替换，但每一次需要替换和被替换的值都不一样，使用此功能进行替换");

            excel.WorkBookToFileStream(fielPath);
            MessageBox.Show("下载成功", "提示", MessageBoxButtons.OK);
        }
    }
    public class ExcelREsult
    {
        public string ReplaceStr { get; set; }
        public string FindStr { get; set; }
    }
}
